package com.example.rpc_core.servers;

import com.example.rpc_core.constance.ProtocolConstant;
import com.example.rpc_core.protocal.ProtocolMessage;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.parsetools.RecordParser;

/**
 * 对原来的buffer进行包装
 */

public class TcpBufferHandlerWrapper implements Handler<Buffer> {
    private final RecordParser recordParser;

    public TcpBufferHandlerWrapper(Handler<Buffer>bufferHandler){
        this.recordParser=initRecordParser(bufferHandler);
    }
    @Override
    public void handle(Buffer buffer) {
        recordParser.handle(buffer);
    }

    private RecordParser initRecordParser(Handler<Buffer> bufferHandler){
        RecordParser ReallyRecordParser = RecordParser.newFixed(ProtocolConstant.MESSAGE_HEADER_LENGTH);
        ReallyRecordParser.setOutput(new Handler<Buffer>() {
            int size=-1;
            Buffer Reallybuffer=Buffer.buffer();
            @Override
            public void handle(Buffer buffer) {
                if (size==-1){
                    //读取消息体长度
                    size=buffer.getInt(13);
                    ReallyRecordParser.fixedSizeMode(size);
                    Reallybuffer.appendBuffer(buffer);
                }else{
                    //写入体信息到结果
                    Reallybuffer.appendBuffer(buffer);
                    bufferHandler.handle(Reallybuffer);

                    //重置一轮
                    ReallyRecordParser.fixedSizeMode(ProtocolConstant.MESSAGE_HEADER_LENGTH);
                    size=-1;
                    Reallybuffer=Buffer.buffer();
                }

            }
        });
        return ReallyRecordParser;

    }
}
